//
//  RegistFirstStepViewController.m
//  QRMaster
//
//  Created by myApple on 15/4/24.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "RegistFirstStepViewController.h"
#import "LineView.h"
#import "RegistLastViewController.h"
#import "PromptInfoView.h"
#import "RequestNetWork.h"
#import "MyRsa.h"
#import "AgreeViewController.h"
#import "Reachability.h"
#import "MZSelectableLabel.h"
#import "validateInputValue.h"

@interface RegistFirstStepViewController ()<UITextFieldDelegate,UIAlertViewDelegate>
{
    UITextField * UserNameTextField;
    UITextField * PassWordTextField;
    UIButton * ResgistBtn;
    
    UIView * userNameLine;
    UIView * passWordLine;
    MZSelectableLabel * promtLabel;
    
    UIImageView * PWDView;
    UIButton * newSeeBtn;
    BOOL emailFlag;
    BOOL passWordFlag;
    
    NSString *registerWay;//注册方式  0表手机，1表示邮箱
}

@end

@implementation RegistFirstStepViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBA(237, 238, 241, 1);
    self.title = NSLocalizedString(@"registByEmail", nil);
    emailFlag = NO;
    passWordFlag = NO;
    [self prepareView];
    // Do any additional setup after loading the view.
}

-(void)prepareView
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hiddenKeyboard) name:@"KCHiddenKeyBoardNotification" object:nil];
    float ScreenWidth = self.view.frame.size.width;
    //    float ScreenHeight = self.frame.size.height;
    float x = 95;
    float y = 71;
    float width = ScreenWidth - x - 16;
    float height = 39;
    
    UserNameTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    UserNameTextField.placeholder = NSLocalizedString(@"mineEmail", nil);
    UserNameTextField.font = [UIFont systemFontOfSize:13.0];
    UserNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    UserNameTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    [self.view addSubview:UserNameTextField];
    UserNameTextField.delegate = self;
//    UIImageView * userNameView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 10, 20, 20)];
//    UIImage * userimag = [UIImage imageNamed:@"36登录_用户"];
//    userNameView.image = userimag;
    UILabel * userLabel = [[UILabel alloc]initWithFrame:CGRectMake(22, 81, 100, 20)];
    userLabel.text = NSLocalizedString(@"mineEmail", nil);
    userLabel.font = [UIFont systemFontOfSize:13.0];
    [self.view addSubview:userLabel];
//    UserNameTextField.leftView = userLabel;
//    UserNameTextField.leftViewMode = UITextFieldViewModeAlways;
    userNameLine = [[LineView alloc]initWithFrame:CGRectMake(16, y+height,UI_SCREEN_WIDTH - 32, 0.5)];
    userNameLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
    [self.view addSubview:userNameLine];
    y += height + 5;
    PassWordTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    PassWordTextField.secureTextEntry = YES;
    PassWordTextField.placeholder = NSLocalizedString(@"passPromt", nil);
    PassWordTextField.delegate = self;
    PassWordTextField.font = [UIFont systemFontOfSize:13.0];
    PassWordTextField.borderStyle = UITextBorderStyleNone;
    PassWordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:PassWordTextField];
    passWordLine = [[LineView alloc]initWithFrame:CGRectMake(16, y+height, UI_SCREEN_WIDTH - 32, 0.5)];
    passWordLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
    [self.view addSubview:passWordLine];
    
    UIImageView * newSeeImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    PassWordTextField.rightViewMode = UITextFieldViewModeAlways;
    PassWordTextField.rightView = newSeeImgView;
    newSeeImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer * newSeeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(seeNewTap)];
    [newSeeImgView addGestureRecognizer:newSeeTap];
    newSeeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    newSeeBtn.frame = CGRectMake(20, 14, 16, 12);
    newSeeBtn.selected = NO;
    newSeeBtn.userInteractionEnabled = NO;
    [newSeeBtn setBackgroundImage:[UIImage imageNamed:@"Browse"] forState:UIControlStateNormal];
    [newSeeBtn setBackgroundImage:[UIImage imageNamed:@"GreenBrowse"] forState:UIControlStateSelected];
    [newSeeImgView addSubview:newSeeBtn];
    
//    UIImageView * passWordView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 10, 20, 20)];
//    UIImage * passWordImg = [UIImage imageNamed:@"36登录_密码"];
//    passWordView.image = passWordImg;
    UILabel * passWordLabel = [[UILabel alloc]initWithFrame:CGRectMake(22, PassWordTextField.frame.origin.y + 10, 100, 20)];
    passWordLabel.text = NSLocalizedString(@"passWord", nil);
    passWordLabel.font = [UIFont systemFontOfSize:13.0];
    [self.view addSubview:passWordLabel];
//    PassWordTextField.leftView = passWordLabel;
//    PassWordTextField.leftViewMode = UITextFieldViewModeAlways;
    
    
    x = 16;
    y += height + 26;
    width = ScreenWidth - 2 * x;
    height = 40;
    ResgistBtn= [UIButton buttonWithType:UIButtonTypeCustom];
    ResgistBtn.frame = CGRectMake(x, y, width, height);
    [ResgistBtn setTitleColor:UIColorFromRGBAndA(0xffffff, 0.5) forState:0];
    [ResgistBtn setBackgroundColor:UIColorFromRGBAndA(0x7dc234, 0.5)];
    [ResgistBtn setTitle:NSLocalizedString(@"registBtn", nil) forState:0];
    ResgistBtn.layer.cornerRadius = 5;
    ResgistBtn.enabled = NO;
    ResgistBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [ResgistBtn addTarget:self action:@selector(resgistClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:ResgistBtn];
    
    x = 20;
    y += height + 20;
    width = ScreenWidth - 2 * x;
    height = 30;
    promtLabel = [[MZSelectableLabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    promtLabel.text = NSLocalizedString(@"agreement", nil);
    promtLabel.numberOfLines = 0;
    promtLabel.textAlignment = NSTextAlignmentLeft;
    promtLabel.font = [UIFont systemFontOfSize:12.0];
    [self.view addSubview:promtLabel];
    
    __weak RegistFirstStepViewController * weakSelf = self;
    promtLabel.selectionHandler = ^(NSRange range,NSString * string)
    {
        AgreeViewController * avc = [[AgreeViewController alloc]init];
        [weakSelf.navigationController pushViewController:avc animated:YES];
    };
    
    NSMutableAttributedString * astr = [[NSMutableAttributedString alloc]initWithString:promtLabel.text];
    [astr addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:12.0],NSFontAttributeName,UIColorFromRGB(0x7dc234),NSForegroundColorAttributeName, nil] range:[promtLabel.text rangeOfString:NSLocalizedString(@"registAgreement", nil)]];
    promtLabel.attributedText = astr;
    [promtLabel setSelectableRange:[[promtLabel.attributedText string]rangeOfString:NSLocalizedString(@"registAgreement", nil)]];
}


#pragma mark ----------- textfielddelegated
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField == UserNameTextField) {
        if (newString.length > 0) {
            emailFlag = YES;
        }
        else
        {
            emailFlag = NO;
        }
    }
    else if (textField == PassWordTextField)
    {
        if (newString.length > 0 ) {
            passWordFlag = YES;
        }
        else
        {
            passWordFlag = NO;
        }
    }
    [self canTapOfRegist];
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == UserNameTextField) {
        UserNameTextField.text = textField.text;
    }
    else
    {
        PassWordTextField.text = textField.text;
    }
}

-(BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == UserNameTextField) {
        emailFlag = NO;
    }
    else
    {
        passWordFlag = NO;
    }
    [self canTapOfRegist];
    return YES;
}

-(void)resgistClick:(UIButton *)btn
{
    [self.view endEditing:YES];
    [self hiddenKeyboard];
    UserNameTextField.text = [UserNameTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (![validateInputValue validateStringIsNull:UserNameTextField.text]) {
        if (![validateInputValue validateEmail:UserNameTextField.text]) {
            [PromptInfoView showMessage:NSLocalizedString(@"AccountError", nil)];
            return;
        }
    }
    else
    {
        [PromptInfoView showMessage:NSLocalizedString(@"errorAccount", nil)];
        return;
    }
    if (![validateInputValue validatePassword:PassWordTextField.text]) {
        [PromptInfoView showMessage:NSLocalizedString(@"loginingPromt", nil)];
        return;
    }
    
    NSString * locaString = NSLocalizedString(@"registPromt", nil);
    NSString *titleInfo;//提示的内容，根据手机号和邮箱去区分
    if(YES == [validateInputValue validateEmail:UserNameTextField.text])
    {
        titleInfo=NSLocalizedString(@"makeSureEmail", nil);
        registerWay=@"1";
    }
    else if (YES == [validateInputValue telePhoneValidate:UserNameTextField.text])
    {
        titleInfo=NSLocalizedString(@"makeSureTelePhone", nil);
        registerWay=@"0";
    }
    NSString * messageString = [NSString stringWithFormat:@"%@%@",locaString,UserNameTextField.text];
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:titleInfo message:messageString delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel", nil) otherButtonTitles:NSLocalizedString(@"alterSure", nil), nil];
    [alert show];
}

#pragma mark --------看密码
-(void)seeNewTap
{
    newSeeBtn.selected = !newSeeBtn.selected;
    if (newSeeBtn.selected) {
        PassWordTextField.secureTextEntry = NO;
    }
    else
    {
        PassWordTextField.secureTextEntry = YES;
    }
}



-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [PassWordTextField resignFirstResponder];
    [UserNameTextField resignFirstResponder];
    if (buttonIndex == 1) {
        [self GetData];
        
    }
}


-(NSString *)getPassword
{
    MyRsa * rsa = [[MyRsa alloc]init];
    if (rsa != nil) {
        NSString * encryptPWD = [rsa RSAEncrypotoTheData:[NSString stringWithFormat:@"12345678%@",PassWordTextField.text] key:publicKeyString];
        encryptPWD = [encryptPWD stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        return encryptPWD;
    }
    else
        return nil;
    
}

-(void)GetData
{
    if ([self IsHaveNetwork]) {
        return;
    }
   [self startWaiting:nil color:nil addToView:self.view];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
//    if ([@"0" isEqualToString:registerWay]==YES) {
//        [postDict setValue:UserNameTextField.text forKey:@"mobile"];
//        [postDict setValue:@"" forKey:@"email"];
//    }
//    else if ([@"1" isEqualToString:registerWay]==YES)
//    {
//        [postDict setValue:@"" forKey:@"mobile"];
        [postDict setValue:UserNameTextField.text forKey:@"email"];
//    }
    [rnk initWithPath:POST(REGISTERVCODE) params:postDict block:^(id downLoadData, id error) {
        [self stopWaiting];
        if ([downLoadData objectForKey:@"data"] != nil &&[@"" isEqualToString:[downLoadData objectForKey:@"data"]]==NO) {
            RegistLastViewController * rlvc = [[RegistLastViewController alloc]init];
            rlvc.passWord = [self getPassword];
            rlvc.mobileNumber = UserNameTextField.text;
            [self.navigationController pushViewController:rlvc animated:YES];
        }
        else if (error != nil) {
            [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
        }
    }];
    
}

#pragma mark ----------- 判断注册按钮是否能够点击
-(void)canTapOfRegist
{
    if (emailFlag && passWordFlag) {
        [self registBtnEnable];
    }
    else
    {
        [self registBtnDisenable];
    }
}


#pragma mark ----------注册按钮点击和不可以点击的两种状态
-(void)registBtnEnable
{
    [ResgistBtn setBackgroundColor:UIColorFromRGB(0x7cd234)];
    [ResgistBtn setTitleColor:UIColorFromRGB(0xffffff) forState:0];
    ResgistBtn.enabled = YES;
}

-(void)registBtnDisenable
{
    [ResgistBtn setBackgroundColor:UIColorFromRGBAndA(0x7cd234, 0.5)];
    [ResgistBtn setTitleColor:UIColorFromRGBAndA(0xffffff,0.5) forState:0];
    ResgistBtn.enabled = NO;
}

-(void)hiddenKeyboard
{
    [UserNameTextField resignFirstResponder];
    [PassWordTextField resignFirstResponder];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"KCHiddenKeyBoardNotification" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
